package com.heima.homeservicemanagementsystem.service.impl;

import cn.hutool.db.DbRuntimeException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.homeservicemanagementsystem.entity.EmployeesAndService;
import com.heima.homeservicemanagementsystem.entity.ServiceServicedetail;
import com.heima.homeservicemanagementsystem.entity.UserAddress;
import com.heima.homeservicemanagementsystem.entity.common.OrderStatusEnum;
import com.heima.homeservicemanagementsystem.mapper.BuyrOrderMapper;
import com.heima.homeservicemanagementsystem.entity.BuyrOrder;
import com.heima.homeservicemanagementsystem.module.Result;
import com.heima.homeservicemanagementsystem.service.BuyrOrderService;
import com.heima.homeservicemanagementsystem.service.EmployeesAndServiceService;
import com.heima.homeservicemanagementsystem.service.ServiceServicedetailService;
import com.heima.homeservicemanagementsystem.service.UserAddressService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.coyote.BadRequestException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单(BuyrOrder)表服务实现类
 *
 * @author makejava
 * @since 2025-04-25 11:36:00
 */
@Slf4j
@Service
public class BuyrOrderServiceImpl extends ServiceImpl<BuyrOrderMapper, BuyrOrder> implements BuyrOrderService {

    private static final String ORDERS_SHARD_KEY_ID_GENERATOR = "1";
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private UserAddressService userAddressService;
    @Resource
    private EmployeesAndServiceService employeesAndServiceService;
    @Resource
    private ServiceServicedetailService serviceServicedetailService;

    private String generateOrderId() {
        //通过Redis自增序列得到序号
        Long id = stringRedisTemplate.opsForValue().increment(ORDERS_SHARD_KEY_ID_GENERATOR, 1);
        //生成订单号   2位年+2位月+2位日+13位序号
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMdd"));
        long orderId = Long.parseLong(date) * 10000000000000L + id;
        return String.valueOf(orderId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createrOrder(BuyrOrder buyrOrder) throws BadRequestException {
        log.info("订单信息", buyrOrder);
        boolean exists = userAddressService.exists(Wrappers.<UserAddress>lambdaQuery().eq(StringUtils.hasLength(buyrOrder.getAddressId()), UserAddress::getUserId, buyrOrder.getUserId()));
        if (!exists) {
            throw new BadRequestException("预约地址异常，无法下单");
        }
//        BuyrOrder orders = new BuyrOrder();
        buyrOrder.setOrderId(generateOrderId());
        buyrOrder.setOrderStatus(OrderStatusEnum.PendingPayment);
        boolean save = this.save(buyrOrder);

        if (!save) {
            throw new DbRuntimeException("下单失败");
        }
        return buyrOrder.getId();
    }

    @Override
    public Result<List<BuyrOrder>> findByServiceIdJson(String userid, String orderstatus) {
        log.info("单个的参数：{},{}", userid, orderstatus);
        // 查询用户的所有服务ID
        QueryWrapper<EmployeesAndService> userIdQuery = new QueryWrapper<EmployeesAndService>().eq("user_id", userid);
        List<EmployeesAndService> list = employeesAndServiceService.list(userIdQuery);

        // 存储所有的 serviceId
        List<String> objects = new ArrayList<>();

        // 获取每个 EmployeesAndService 对应的服务ID
        for (EmployeesAndService employeesAndService : list) {
            QueryWrapper<ServiceServicedetail> serviceIdQuery = new QueryWrapper<>();
            serviceIdQuery.eq("serviceId", employeesAndService.getServiceId());

            List<ServiceServicedetail> serviceDetails = serviceServicedetailService.list(serviceIdQuery);

            // 将查询出的 serviceId 存入 objects 中
            List<String> collect = serviceDetails.stream()
                    .map(ServiceServicedetail::getDetailid)
                    .collect(Collectors.toList());
            objects.addAll(collect);
        }

        // 构建查询 BuyrOrder 的 QueryWrapper
        QueryWrapper<BuyrOrder> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("order_status", orderstatus);
        // 使用多个 OR 条件来查询任意包含的 service_id
        StringBuilder queryBuilder = new StringBuilder();
        for (int i = 0; i < objects.size(); i++) {
            if (i > 0) {
                queryBuilder.append(" OR ");
            }
            queryBuilder.append("JSON_CONTAINS(service_id, '\"").append(objects.get(i)).append("\"')");
        }

        // 将 OR 条件添加到查询中
        orderQueryWrapper.apply("(" + queryBuilder.toString() + ")");

        // 执行查询

        List<BuyrOrder> orders = list(orderQueryWrapper);

        for (BuyrOrder order : orders) {
            QueryWrapper<UserAddress> wrapper = new QueryWrapper<>();
            wrapper.eq("id", order.getAddressId());
            UserAddress one = userAddressService.getOne(wrapper);
            order.setUserAddress(one);
        }


        // 日志输出查询结果
        log.info("list1: {}", orders);

        return Result.success(orders);
    }

    @Override
    public Result<List<BuyrOrder>> findByuserIdJson(String userid) {
        // 查询用户的所有服务ID
        QueryWrapper<EmployeesAndService> userIdQuery = new QueryWrapper<EmployeesAndService>().eq("user_id", userid);
        List<EmployeesAndService> list = employeesAndServiceService.list(userIdQuery);

        // 存储所有的 serviceId
        List<String> objects = new ArrayList<>();

        // 获取每个 EmployeesAndService 对应的服务ID
        for (EmployeesAndService employeesAndService : list) {
            QueryWrapper<ServiceServicedetail> serviceIdQuery = new QueryWrapper<>();
            serviceIdQuery.eq("serviceId", employeesAndService.getServiceId());

            List<ServiceServicedetail> serviceDetails = serviceServicedetailService.list(serviceIdQuery);

            // 将查询出的 serviceId 存入 objects 中
            List<String> collect = serviceDetails.stream()
                    .map(ServiceServicedetail::getDetailid)
                    .collect(Collectors.toList());
            objects.addAll(collect);
        }

        // 构建查询 BuyrOrder 的 QueryWrapper
        QueryWrapper<BuyrOrder> orderQueryWrapper = new QueryWrapper<>();

        // 使用多个 OR 条件来查询任意包含的 service_id
        StringBuilder queryBuilder = new StringBuilder();
        for (int i = 0; i < objects.size(); i++) {
            if (i > 0) {
                queryBuilder.append(" OR ");
            }
            queryBuilder.append("JSON_CONTAINS(service_id, '\"").append(objects.get(i)).append("\"')");
        }

        // 将 OR 条件添加到查询中
        orderQueryWrapper.apply(queryBuilder.toString());
//        orderQueryWrapper.eq("order_status", orderstatus);
        // 执行查询

        List<BuyrOrder> orders = list(orderQueryWrapper);

        for (BuyrOrder order : orders) {
            QueryWrapper<UserAddress> wrapper = new QueryWrapper<>();
            wrapper.eq("id", order.getAddressId());
            UserAddress one = userAddressService.getOne(wrapper);
            order.setUserAddress(one);
        }


        // 日志输出查询结果
        log.info("list1: {}", orders);

        return Result.success(orders);
    }
}

